package com.itheima.es_goods_demo.utils;

import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;


public class KibanaUtil {
    private static RestHighLevelClient client;
    private static BulkRequest bulkRequest;

    public static void register(RestHighLevelClient RestHighLevelClient){
        client=RestHighLevelClient;
    }

    public static void bulkAdd(String index,String id,String json){
        if (bulkRequest==null)
            bulkRequest=new BulkRequest();
        bulkRequest.add(new IndexRequest(index).id(id).source(json, XContentType.JSON));

    }
    public static void bulkExport(){
        try {
            BulkResponse responses = client.bulk(bulkRequest, RequestOptions.DEFAULT);
            bulkRequest=null;
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void createIndexAndMapping(String index,String indexMapping){
        CreateIndexRequest request = new CreateIndexRequest(index);

        request.source(indexMapping, XContentType.JSON);


        try {
            CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void deleteIndex(String index){
        DeleteIndexRequest request = new DeleteIndexRequest(index);
        try {
            AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String getDocument(String index,String id) throws IOException {
        GetRequest getRequest = new GetRequest(index, id);

            GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
            return getResponse.getSourceAsString();


    }

    public static boolean isIndexExits(String index){
        try {
            return client.indices().exists(new GetIndexRequest(index),RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        };
        return false;
    }




}
